import {Controller, Ctx, Get, Use, Param, Body, Delete, Put, Post, QueryParam, File} from 'trafficlight';
import {getRepository} from "typeorm";
import {User} from "../entity/User"
import {aesEn} from "../utils/cryptoUitl"
import {success} from "../utils/respFormat"
import {auth} from "../middle/auth"
import {createToken} from "../utils/jwt"

import redisCli from '../utils/redis'

@Controller('/user')
export class UserCtl {

    private db = getRepository(User)

    @Get('/redisTest')
    async redisTest(@Ctx() ctx) {
        await redisCli.hmset("mp", "xxx", "123")
        const val = await redisCli.hmget("mp","xxx")
        console.log(val)
        return success(val)
    }

    @Get('/aes')
    @Use(auth(false))
    async sessionTest(@Ctx() ctx) {
        console.log("uid ==>> ",ctx.Map.uid)
        return success("success")
    }

    @Get('/all')
    async getAll() {
        const data = this.db.find()
        return success(data)
    }

    @Get('/:id')
    async getOne(@Param('id') id: number) {
        const data = await this.db.findOne(id)
        return success(data)
    }

    @Post("/login")
    async login(@Body() body:User) {
        body.password = aesEn(body.password)
        const user = await this.db.findOne({username: body.username, password: body.password})
        const token = createToken({uid: `${user.id}`})
        return success(token)
    }

    @Put('/register')
    async register(@Body() body: User) {
        body.createdAt = new Date()
        body.password = aesEn(body.password)
        const user = await this.db.save(body)
        const token = createToken({uid: `${user.id}`})
        return success(token)
    }
}